<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> 设备管理 </span>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleForm({})" v-auth="'device:management:inDeviceManagement:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
        <a-button
         @click="handleDeviceImport"
         >
          设备导入
        </a-button>
        <a-button @click="handleMaintenance">
          批量维护
        </a-button>
        <a-button @click="handleDeleteList">
          批量删除
        </a-button>
      </template> 
      <template #firstColumn="{ record }">
        <a @click="handleForm({ tid: record.tid })">
          {{ record.equipmentName }}
        </a>
      </template>
      <!-- 新增 action 插槽 -->
      <template #action="{ record }">
        <a-button 
        @click="handleForm({ tid: record.tid })" 
        v-auth="'device:management:inDeviceManagement:edit'" 
        type="text"
        >
          <span style="font-size:14px; color: #52c41a;">编辑</span>
        </a-button>
        <a-button 
        @click="handleFormDetail({ tid: record.tid })" 
        type="text"
        >
          <span style="font-size: 14px; color: #4169E1;">详情</span>
        </a-button>
        <!-- 添加 Popconfirm 组件 -->
        <Popconfirm
          title="是否确认删除数据"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete(record)"
          @cancel="handleCancel"
        >
          <a-button 
          v-auth="'device:management:inDeviceManagement:edit'" 
          type="text"
          style="color: red;"
          >
            <span style="font-size:14px;">删除</span>
          </a-button>
        </Popconfirm>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormDeatil @register="registerDrawerDetail" @success="handleSuccess" />
    <!-- 使用 v-model 绑定 isUploadModalVisible -->
    <UploadModal v-model="isUploadModalVisible" @download="handleDownload" />
    <UpdateDevice :deviceList="selectedRowKeysRef" @register="registerModalUpdate" />
  </div>
</template>

<script lang="ts" setup name="ViewsDeviceManagementInDeviceManagementList">
  import { unref, ref, computed, watch, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { inDeviceManagementDelete, inDeviceManagementListData, uploadDevice,deleteByList } from '/@/api/device.management/inDeviceManagement';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { officeTreeData } from '/@/api/sys/office';
  import { unitRegionListData } from '/@/api/unitmanage/unitRegion';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { inEquipmentTypeListData } from '/@/api/device.management/inEquipmentType';
  import InputForm from './form.vue';
  import FormDeatil from './formDetail.vue';
  import { useDataFetching } from '/@/utils/Deduplicate';
  import UploadModal from './UploadModal.vue'; // 引入设备上传模态框组件
  import UpdateDevice from './updateDevice.vue'; // 引入设备维护信息组件
  import { Popconfirm } from 'ant-design-vue'; // 引入 Popconfirm 组件

  // 使用组合式函数
  const { uniqueArray, getAllData } = useDataFetching(); 
  const { t } = useI18n('device.management.inDeviceManagement');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('设备管理表管理'),
  };
  const selectedRowKeysRef = ref<string[]>([]);
  const EquipmentName = ref('');
  const EquipmentParams = computed(() => {
    const params = {
      equipmentName: EquipmentName.value,
    }
    console.log('equipmentParams 中的 equipmentName 值:', params.equipmentName);
    return params;
  })

  const RegionName = ref('');
  const RegionParams = computed(() => {
   return {
    name: RegionName.value,
   }
  })
  const EnterpriseParams = ref<Recordable>({
     name:''
    });
const EquipmentTypeName=ref('')
 const EquipmentTypeParams = computed(()=>{
  const params={
    equipmentName:EquipmentTypeName.value
  }
  return params
 })

  const searchForm: FormProps = {
    baseColProps: { md: 4, lg: 4 },
    labelWidth: 90,
    schemas: [
      {
        label: t(''),
        field: 'equipmentName',
        // fieldLabel: 'equipmentName',
        component: 'Input',
        componentProps: {
          placeholder: t('请输入设备名称'),
          
        },
      },
      {
        label: t(''),
        field: 'equipmentTypeId',
        fieldLabel: 'equipmentType',
        component: 'Select',
        componentProps: () => {
        return {
          placeholder: t('请选择设备类型'),
          api: inEquipmentTypeListData,
          params: EquipmentTypeParams.value,
          fieldNames: { label: 'equipmentName', value: 'equipmentCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EquipmentTypeName.value = value;
            console.log(EquipmentTypeParams.value);
          },
        };
      },
      },
      {
        label: t(''),
        field: 'equipmentCode',
        component: 'Input',
        componentProps: {
          placeholder: t('请输入设备编码'),
        },
      },
      // {
      //   label: t(''),
      //   field: 'equipmentTypeId',
      //   fieldLabel: 'equipmentType',
      //   component: 'TreeSelect',
      //   componentProps: {
      //     placeholder: t('请输入设备类型'),
      //     dictType: '	testing_equipment_type',
      //     allowClear: true,
      //   },
      // },
      {
        label: t(''),
        field: 'enterpriseId',
        fieldLabel: 'enterpriseName',
        component: 'Select',
        componentProps: () => {
        return {
          placeholder: t('请输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
      },
      {
        label: t(''),
        field: 'regionId',
        fieldLabel: 'regionName',
        component: 'TreeSelect',
        componentProps: {
          placeholder: t('请选择区域名称'),
          api: unitRegionListData,
          resultField: 'list',
          resultFieldNames: { label: 'name', value: 'name' },
          params: RegionParams,
          allowClear:true,
          immediate:false,
          each:false,
          showSelect:true,
          optionFilterProp: 'label',
          showSearch:true,
          onSearch: (value) => {
            RegionName.value = value;
          // console.log('输入的值:', RegionName.value);
          reload()
        },
        },
      },
      {
        label: t(''),
        field: 'realStatus',
        component: 'Select',
        componentProps: {
          placeholder: t('请选择设备在线状态'),
          options: [
            { label: t('设备在线'), value: t('设备在线') },
            { label: t('设备离线'), value: t('设备离线') },
          ],
        },
      },
      {
        label: t(''),
        field: 'status',
        component: 'Select',
        componentProps: {
          placeholder: t('请选设备状态'),
          allowClear: true,
          // onChange: handleSuccess,
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('设备名称'),
      dataIndex: 'equipmentName',
      key: 'a.equipment_name',
      sorter: true,
      width: 230,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('设备编码'),
      dataIndex: 'equipmentCode',
      key: 'a.equipment_code',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('设备类型'),
      dataIndex: 'equipmentType',
      key: 'a.equipment_type',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('企业名称'),
      dataIndex: 'enterpriseName',
      key: 'a.enterprise_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('安装建筑名称'),
      dataIndex: 'buildName',
      key: 'a.build_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('区域名称'),
      dataIndex:'regionName',
      key: 'a.region_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('当前设备状态'),
      dataIndex: 'realStatus',
      key: 'a.real_status',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      key: 'a.status',
      sorter: true,
      width: 130,
      align: 'center',
      // dictType: 'sys_search_status',
    }
  ];

  const actionColumn: BasicColumn = {
    width: 200,
    slots: { customRender: 'action' }, // 使用自定义插槽
  };

  let TidFromUrl = '';

  const [registerTable, { reload, getForm }] = useTable({
  rowSelection: {
    onChange: (selectedRowKeys: string[], _selectedRows: Recordable[]) => {
      selectedRowKeysRef.value = selectedRowKeys;
    },
  },
  api: inDeviceManagementListData,
  beforeFetch: (params) => {
    const Tid = router.currentRoute.value.query.tid;
    if (Tid) {
      TidFromUrl = decodeURIComponent(Tid as string);
      params.tid = TidFromUrl;
    }
    console.log('params', params);
    return params;
  },
  columns: tableColumns,
  actionColumn: actionColumn,
  formConfig: searchForm,
  showTableSetting: true,
  useSearchForm: true,
  canResize: true,
});

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerDetail, { openDrawer: openDrawerDetail }] = useDrawer();
  const [registerModalUpdate, { openModal: openModalUpdate }] = useModal();

  const isUploadModalVisible = ref(false);

  function handleMaintenance() {
    if (selectedRowKeysRef.value.length === 0) {
      showMessage('请先勾选需要配置的设备');
      return;
    }
    openModalUpdate(true);
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handleFormDetail(record: Recordable) {
    openDrawerDetail(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { tid: record.tid };
    const res = await inDeviceManagementDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  const handleDeviceImport = () => {
    isUploadModalVisible.value = true;
  };

  async function handleDeleteList() {
    if (selectedRowKeysRef.value.length === 0) {
      showMessage('请先勾选需要配置的设备');
      return;
    }
    const deviceList = { deviceList: selectedRowKeysRef.value };
    await deleteByList(deviceList).then((res) => {
      showMessage(res.message);
    });
    handleSuccess({});
  }

  const handleDownload = () => {
    // 这里的API地址需替换为实际的后端接口地址
    const downloadUrl = '/resource/devieceTemplete/设备批量导入模板.xlsx';
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'device_import_template.xlsx';
    link.click();
  };

  function handleCancel() {
    // 取消删除操作时的处理逻辑，这里可以不做任何处理，仅为了响应取消事件
    console.log('取消删除操作');
  }

  onMounted(() => {
  // 确保在组件挂载时重新加载数据
  reload();
});

</script>

<style scoped less>
</style>